import Vue from 'vue'
import VueRouter from 'vue-router'
import store from '@/store'
const Login = () => import('@/views/Login')
const Layout = () => import('@/views/Layout')
const User = () => import('@/views/User')
const Home = () => import('@/views/Home')
const Video = () => import('@/views/Video')
const Search = () => import('@/views/Search')
const SearchResult = () => import('@/views/Search/SearchResult')
const Detail = () => import('@/views/Article')
const EditUser = () => import('@/views/User/EditUser')
const Chat = () => import('@/views/User/Chat')
Vue.use(VueRouter)
// 解决router跳转bug
const originalPush = VueRouter.prototype.push
VueRouter.prototype.push = function push (location) {
  return originalPush.call(this, location).catch(err => err)
}

const routes = [
  {
    path: '/login', // 登录路由
    component: Login
  },
  {
    path: '/search', // 搜索路由
    component: Search
  },
  {
    path: '/searchResult', // 搜索到关键字多的路由
    component: SearchResult
  },
  {
    path: '/chat', // 小智同学
    component: Chat
  },
  {
    path: '/detail',
    component: Detail
  },
  {
    path: '/editUser',
    component: EditUser
  },
  {
    path: '/', // 首页
    component: Layout,
    children: [
      {
        path: 'user',
        component: User
      },
      {
        path: '',
        component: Home,
        meta: { isKeepAlive: true }
      },
      {
        path: 'video',
        component: Video
      }
    ]
  }
]

const router = new VueRouter({
  routes
})
// 增加导航守卫做权限控制
// 1. 如果跳转到的是其它页面直接放行
// 2. 如果跳转到的是'我的'页面，增加判断逻辑，如果有token则放行，如果没有则跳回到登录页面
router.beforeEach((to, from, next) => {
  console.log(to)
  // to: 到哪里去  目标路由对象
  // from: 从哪里来  来源路由对象
  // next: 放行函数
  if (to.path.startsWith('/user')) {
    // 当前要去往我的页面需要做额外的判断
    const token = store.state.tokenInfo.token
    if (token) {
      next()
    } else {
      // 跳回到登录页面之前记录一下当前页面是什么
      next({
        path: '/login',
        query: {
          sourceFrom: to.fullPath
        }
      })
    }
  } else {
    // 其它页面
    next()
  }
})
export default router
